﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json.Linq;
using JDCloudSDK.Core.Auth;
using JDCloudSDK.Core.Extensions;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;

namespace JingDong.Open.Platform
{
    public class GetOrderSensitiveInfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            var request = dataset.GetJsonObject("request");
            var constant = dataset.GetJsonObject("constant");
            var jingdongHufuAPIConfig = constant.GetNecessaryJsonObject("jingdongHufuAPIConfig", "constant");
            //var eComOrderSensitiveConfig = constant.GetNecessaryJsonObject("eComOrderSensitiveConfig", "constant");

            string eShopCode = request.GetJsonObjectStringValue("eShopCode");
            string orderId = request.GetJsonObjectStringValue("orderId");
            bool decrypt = request.GetJsonObjectBooleanValue("decrypt", true);

            if (string.IsNullOrWhiteSpace(eShopCode) || string.IsNullOrWhiteSpace(orderId))
                throw new Exception();

            if (orderId.Contains("-"))
            {
                var orderIds = orderId.Split('-');
                if (orderIds.Length == 2)
                    orderId = orderIds[0];
            }

            if (orderId.Contains("X"))
            {
                var orderIds = orderId.Split('X');
                if (orderIds.Length == 2)
                    orderId = orderIds[0];
            }

            //string parentPath = string.Format("constant.eComOrderSensitiveConfig.{0}", eShopCode);
            //var config = eComOrderSensitiveConfig.GetJsonObject(eShopCode);

            //if (config == null)
            //{
            //    var eplatform = dataset.GetJsonObjectValue("eplatform");
            //    if (eplatform != null && eplatform.Type == JTokenType.Array && eplatform.HasValues && eplatform.First.Type == JTokenType.Object)
            //    {
            //        string ePlatformCode = (eplatform.First as JObject).GetJsonObjectStringValue("ePlatformCode");
            //        config = eComOrderSensitiveConfig.GetJsonObject(ePlatformCode);
            //    }
            //}

            //if (config == null)
            //    throw new ConfigException("{0} is null or not an object", parentPath);

            string api = "jingdong.hufu.order.getSensitiveData";//config.GetNecessaryJsonObjectStringValue("api", parentPath);
            string url = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("url", "constant.jingdongHufuAPIConfig");
            string appkey = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("app_key", "constant.jingdongHufuAPIConfig");
            string appsecret = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("app_secret", "constant.jingdongHufuAPIConfig");
            string customerId = jingdongHufuAPIConfig.GetNecessaryJsonObjectStringValue("customerid", "constant.jingdongHufuAPIConfig");
            var proxy = jingdongHufuAPIConfig.GetJsonObjectValue("proxy");

            var jsonContent = new JObject() { { "orders_nos", orderId }, { "token", eShopCode }, { "decrypt", decrypt } };

            var credentials = new Credentials(appkey, appsecret);

            try
            {
                var proxyHttpClientHandler = new HttpClientHandler();

                if (proxy != null && proxy.Type == JTokenType.String && !string.IsNullOrWhiteSpace(proxy.ToString()) && proxy.ToString().IndexOf(":") > -1)
                {
                    string[] hostAndPort = proxy.ToString().Split(':');
                    int port = 0;
                    if (int.TryParse(hostAndPort[1], out port))
                    {
                        proxyHttpClientHandler.Proxy = new WebProxy(hostAndPort[0], port);
                        proxyHttpClientHandler.UseProxy = true;
                    }
                }
                else if (proxy != null && proxy.Type == JTokenType.Boolean && !proxy.Value<bool>())
                {
                    proxyHttpClientHandler.Proxy = null;
                    proxyHttpClientHandler.UseProxy = false;
                }

                using (HttpClient httpClient = new HttpClient(proxyHttpClientHandler))
                {
                    string fullurl = string.Format(url + "?app_key={0}&customerId={1}&method={2}", appkey, customerId, api);
                    var content = new StringContent(jsonContent.ToString(Newtonsoft.Json.Formatting.None), Encoding.UTF8, "application/json");
                    var response = httpClient.DoSign(credentials, "xohk7ybhwien").PostAsync(fullurl, content).Result;
                    var responseString = response.Content?.ReadAsStringAsync().Result;
                    var responseObject = JObject.Parse(responseString);
                    if (responseObject.GetJsonObjectStringValue("code") != "0000")
                        throw ExceptionHelper.GenException("@E110000002", responseObject.GetJsonObjectStringValue("msg"));
                    var orderSensitiveInfo = responseObject.GetJsonObject("orderSensitiveInfo");
                    var orderList = orderSensitiveInfo.GetJsonObjectValue("orderList");
                    if (orderList != null && orderList.Type == JTokenType.Array)
                    {
                        fullurl = string.Format(url + "?app_key={0}&customerId={1}&method={2}", appkey, customerId, "jingdong.hufu.order.popOrderGet");
                        foreach (var item in orderList as JArray)
                        {
                            if (item is JObject)
                            {
                                var order = item as JObject;
                                var oaid = order.GetJsonObjectStringValue("oaid");
                                if (string.IsNullOrWhiteSpace(oaid))
                                    oaid = order.GetJsonObjectStringValue("desen_mobile");
                                if (string.IsNullOrWhiteSpace(oaid))
                                    oaid = order.GetJsonObjectStringValue("desen_telephone");
                                order.Remove("desen_mobile");
                                order.Remove("desen_telephone");

                                if (string.IsNullOrWhiteSpace(oaid))
                                {
                                    string orders_no = order.GetJsonObjectStringValue("orders_no");
                                    if (!string.IsNullOrWhiteSpace(orders_no))
                                    {
                                        jsonContent = new JObject() { { "order_id", orders_no }, { "token", eShopCode } };
                                        var content2 = new StringContent(jsonContent.ToString(Newtonsoft.Json.Formatting.None), Encoding.UTF8, "application/json");
                                        var response2 = httpClient.DoSign(credentials, "xohk7ybhwien").PostAsync(fullurl, content2).Result;
                                        var responseString2 = response2.Content?.ReadAsStringAsync().Result;
                                        var responseObject2 = JObject.Parse(responseString2);
                                        if (responseObject2.GetJsonObjectStringValue("code") == "0000")
                                        {
                                            oaid = responseObject2.GetJsonObject("orderInfo").GetJsonObject("consigneeInfo").GetJsonObjectStringValue("desen_mobile");
                                            if (string.IsNullOrWhiteSpace(oaid))
                                                oaid = responseObject2.GetJsonObject("orderInfo").GetJsonObject("consigneeInfo").GetJsonObjectStringValue("desen_telephone");
                                        }
                                    }
                                }

                                order["oaid"] = oaid;
                            }
                        }
                    }
                    return orderList;
                }
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("JingDong GetOrderSensitiveInfo fail: " + ex.Message);
                throw new Exception("@E110000001");
            }
            
        }
    }
}
